<template>
  <div class="app-container home">
    <!-- 角色权限判断：只有学生端(roleId=3)才显示内容 -->
    <div v-if="userInfo && userInfo.roles && userInfo.roles[0] && userInfo.roles[0].roleId === 3">
      <!-- 待测评任务和测评记录区域 -->
      <el-row :gutter="20" class="list-container">
        <!-- 待测评任务 -->
        <el-col :xs="24" :sm="24" :md="12">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>待测评任务</span>
              <el-button style="float: right; padding: 3px 0" type="text" @click="viewAllTodos">查看全部</el-button>
            </div>
            <div class="task-list">
              <el-table v-loading="todoLoading" :data="todoList" style="width: 100%"
                :header-cell-style="{ background: '#f6f6f6' }" size="small" :max-height="tableMaxHeight">
                <el-table-column label="任务名称" prop="taskName" show-overflow-tooltip></el-table-column>
                <el-table-column label="开始日期" prop="startTime" width="150"></el-table-column>
                <el-table-column label="截止日期" prop="endTime" width="150"></el-table-column>
                <el-table-column label="操作" width="100" fixed="right">
                  <template slot-scope="scope">
                    <el-button 
                      size="mini" 
                      type="text" 
                      @click="handleTodoTask(scope.row)"
                      :disabled="isTaskExpired(scope.row.endTime)"
                      :class="{ 'expired-task': isTaskExpired(scope.row.endTime) }"
                    >
                      {{ isTaskExpired(scope.row.endTime) ? '已过期' : '开始测评' }}
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              <div class="pagination-container">
                <el-pagination background @size-change="handleTodoSizeChange" @current-change="handleTodoCurrentChange"
                  :current-page="todoQuery.pageNum" :page-sizes="[5, 10, 20]" :page-size="todoQuery.pageSize"
                  layout="total, sizes, prev, pager, next" :total="todoTotal">
                </el-pagination>
              </div>
            </div>
          </el-card>
        </el-col>

        <!-- 测评记录 -->
        <el-col :xs="24" :sm="24" :md="12">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>测评记录</span>
              <el-button style="float: right; padding: 3px 0" type="text" @click="viewAllRecords">查看全部</el-button>
            </div>
            <div class="task-list">
              <el-table v-loading="doneLoading" :data="doneList" style="width: 100%"
                :header-cell-style="{ background: '#f6f6f6' }" size="small" :max-height="tableMaxHeight">
                <el-table-column label="任务名称" prop="taskName" show-overflow-tooltip>
                </el-table-column>
                <el-table-column label="开始时间" prop="startTime" width="150">
                </el-table-column>
                <el-table-column label="结束时间" prop="endTime" width="150">
                </el-table-column>
                <el-table-column label="操作" width="100" fixed="right">
                  <template slot-scope="scope">
                    <el-button size="mini" type="text" @click="viewTaskDetail(scope.row)">查看详情</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <div class="pagination-container">
                <el-pagination background @size-change="handleDoneSizeChange" @current-change="handleDoneCurrentChange"
                  :current-page="doneQuery.pageNum" :page-sizes="[5, 10, 20]" :page-size="doneQuery.pageSize"
                  layout="total, sizes, prev, pager, next" :total="doneTotal">
                </el-pagination>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    
    <!-- 非学生端显示暂无数据 -->
    <div v-else class="no-data-container">
      <el-empty description="暂无数据" :image-size="200"></el-empty>
    </div>
  </div>
</template>

<script>
import { getTodoPendingList,getCompleteList } from '@/api/system/assess'
import { getInfo } from '@/api/login'
export default {
  name: "Index",
  data() {
    return {
      // 版本号
      version: "3.8.9",
      // 表格最大高度，用于适配屏幕
      tableMaxHeight: 300,
      // 当前用户信息
      userInfo: null,
      // 待办列表
      todoLoading: false,
      todoList: [],
      todoTotal: 0,
      todoQuery: {
        pageNum: 1,
        pageSize: 5
      },
      // 已办列表
      doneLoading: false,
      doneList: [],
      doneTotal: 0,
      doneQuery: {
        pageNum: 1,
        pageSize: 5
      }
    };
  },
  created() {
    this.getUserInfo();
    this.handleResize();
    window.addEventListener('resize', this.handleResize);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
  },
  methods: {
    // 获取用户信息
    async getUserInfo() {
      try {
        const response = await getInfo();
        this.userInfo = response.user;
        console.log('当前用户信息:', this.userInfo.roles[0].roleId);

        // 1  超级管理员
        // 2  教师端
        // 3 学生端
        // 4 学校端
        // 5 教育局端
        
        // 只有学生端才加载数据
        if (this.userInfo.roles[0].roleId === 3) {
          this.getTodoList();
          this.getDoneList();
        }
      } catch (error) {
        console.error('获取用户信息失败:', error);
      }
    },
    goTarget(href) {
      this.$router.push('/questionnaire');
    },
    openQuestionnaire() {
      this.$router.push('/questionnaire');
    },
    // 调整表格高度适配屏幕
    handleResize() {
      const clientHeight = document.documentElement.clientHeight;
      this.tableMaxHeight = clientHeight - 300; // 根据实际情况调整
      if (this.tableMaxHeight < 200) {
        this.tableMaxHeight = 200;
      }
    },
    // 检查任务是否过期
    isTaskExpired(endTime) {
      if (!endTime) return false;
      const now = new Date();
      const endDate = new Date(endTime);
      return now > endDate;
    },
    // 查看全部待测评任务
    viewAllTodos() {
      this.$router.push({
        path: '/assessment/list',
        query: {
          type: 'todo',
          title: '待测评任务'
        }
      });
    },
    // 查看全部测评记录
    viewAllRecords() {
      this.$router.push({
        path: '/assessment/list',
        query: {
          type: 'record',
          title: '测评记录'
        }
      });
    },
    getTaskTypeTag(type) {
      const typeMap = {
        '心理测评': 'primary',
        '心理咨询': 'success',
        '心理辅导': 'warning',
        '其他': 'info'
      };
      return typeMap[type] || '';
    },
    // 获取待办列表
    getTodoList() {
      this.todoLoading = true;
      getTodoPendingList({
        pageNum: this.todoQuery.pageNum,
        pageSize: this.todoQuery.pageSize
      }).then(response => {
        if (response.code === 200) {
          this.todoList = response.rows;
          this.todoTotal = response.total;
        } else {
          this.$message.error(response.msg || '获取待办列表失败');
        }
      }).catch(error => {
        console.error('获取待办列表出错', error);
        this.$message.error('获取待办列表失败，请稍后重试');
      }).finally(() => {
        this.todoLoading = false;
      });
    },
    // 获取已办列表
    getDoneList() {
      this.doneLoading = true;
      getCompleteList({
        pageNum: this.doneQuery.pageNum,
        pageSize: this.doneQuery.pageSize
      }).then(response => {
        if (response.code === 200) {
          this.doneList = response.rows;
          this.doneTotal = response.total;
        } else {
          this.$message.error(response.msg || '获取已办列表失败');
        }
      }).catch(error => {
        console.error('获取已办列表出错', error);
        this.$message.error('获取已办列表失败，请稍后重试');
      }).finally(() => {
        this.doneLoading = false;
      });
    },
    // 处理待办任务
    handleTodoTask(row) {
      // 检查必要参数是否存在
      if (!row || !row.id) {
        this.$message.error('任务信息不完整，无法打开');
        return;
      }
      
      // 检查是否有scaleIds
      if (!row.scaleIds) {
        this.$message.error('该任务没有关联量表，无法填写');
        return;
      }
      
      // 跳转到测评引导页面
      this.$router.push({
        path: '/assessment/guide',
        query: {
          id: row.id,
          scaleId: row.scaleIds,
          taskName: row.taskName
        }
      });
    },
    // 查看任务详情
    viewTaskDetail(row) {
      // 检查必要参数是否存在
      if (!row || !row.id) {
        this.$message.error('任务信息不完整，无法查看');
        return;
      }
      
      // 检查是否有scaleIds
      if (!row.scaleIds) {
        this.$message.error('该任务没有关联量表，无法查看');
        return;
      }
      
      // 跳转到结果页面，传递参数
      window.open(`/questionnaire?scaleId=${row.scaleIds}&taskId=${row.id}&viewType=result`);
    },
    // 待办列表分页处理
    handleTodoSizeChange(val) {
      this.todoQuery.pageSize = val;
      this.getTodoList();
    },
    handleTodoCurrentChange(val) {
      this.todoQuery.pageNum = val;
      this.getTodoList();
    },
    // 已办列表分页处理
    handleDoneSizeChange(val) {
      this.doneQuery.pageSize = val;
      this.getDoneList();
    },
    handleDoneCurrentChange(val) {
      this.doneQuery.pageNum = val;
      this.getDoneList();
    }
  }
};
</script>

<style scoped lang="scss">
.home {
  blockquote {
    padding: 10px 20px;
    margin: 0 0 20px;
    font-size: 17.5px;
    border-left: 5px solid #eee;
  }

  hr {
    margin-top: 20px;
    margin-bottom: 20px;
    border: 0;
    border-top: 1px solid #eee;
  }

  .col-item {
    margin-bottom: 20px;
  }

  ul {
    padding: 0;
    margin: 0;
  }

  font-family: "open sans",
  "Helvetica Neue",
  Helvetica,
  Arial,
  sans-serif;
  font-size: 13px;
  color: #676a6c;
  overflow-x: hidden;

  ul {
    list-style-type: none;
  }

  h4 {
    margin-top: 0px;
  }

  h2 {
    margin-top: 10px;
    font-size: 26px;
    font-weight: 100;
  }

  p {
    margin-top: 10px;

    b {
      font-weight: 700;
    }
  }

  .update-log {
    ol {
      display: block;
      list-style-type: decimal;
      margin-block-start: 1em;
      margin-block-end: 1em;
      margin-inline-start: 0;
      margin-inline-end: 0;
      padding-inline-start: 40px;
    }
  }

  // 待办和已办列表样式
  .list-container {
    margin-top: 20px;

    .box-card {
      margin-bottom: 20px;
    }

    .task-list {
      min-height: 300px;
      
      // 过期任务样式
      .expired-task {
        color: #c0c4cc !important;
        cursor: not-allowed !important;
        
        &:hover {
          color: #c0c4cc !important;
        }
      }
    }

    .pagination-container {
      padding: 10px 0;
      text-align: right;
    }

    // 移动端样式优化
    @media (max-width: 768px) {
      .el-pagination {
        justify-content: center;
        text-align: center;

        .el-pagination__sizes {
          display: none !important;
        }
      }
    }
  }
}
</style>
